<template>
  <div class="gi_table_page">
    <GiTable
        row-key="id"
        :data="dataList"
        :columns="columns"
        :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="pagination"
        :disabled-tools="['size']"
        :disabled-column-keys="['name']"
        @refresh="search"
    >

      <template #toolbar-left>
        <a-select
            v-model="queryForm.platform"
            :options="platform_type"
            placeholder="请选择平台"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <a-select
            v-model="queryForm.channel"
            :options="channel_type"
            placeholder="请选择渠道"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <a-input-search v-model="queryForm.song" placeholder="请输入歌曲/歌手/专辑" allow-clear @search="search"/>
        <a-select
            v-model="queryForm.status"
            :options="settlement_status"
            placeholder="请选择状态"
            allow-clear
            style="width: 150px"
            @change="search"
        />
        <a-select
            v-model="queryForm.belongTo"
            :options="username_type"
            placeholder="请选择用户"
            allow-clear
            style="width: 150px"
            @change="search"
        />

        <a-range-picker
            mode="month"
            v-model="queryForm.payDateStart"
            allow-clear
            :disabledDate="(current) => dayjs(current).isAfter(dayjs())"
            @change="search"/>

        <!--        <DateRangePicker v-model="queryForm.payDateStart" @change="search" />-->

        <a-button @click="reset">
          <template #icon>
            <icon-refresh/>
          </template>
          <template #default>重置</template>
        </a-button>
        <a-button v-permission="['settlement:report:import']" @click="onImport">
          <template #icon>
            <icon-upload/>
          </template>
          <template #default>导入</template>
        </a-button>
      </template>

      <template #toolbar-right>
        <a-button v-permission="['settlement:report:create']" type="primary" @click="onAdd">
          <template #icon>
            <icon-plus/>
          </template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['settlement:report:export']" v-show="queryForm.payDateStart  && dataList.length"
                  @click="onExport">
          <template #icon>
            <icon-download/>
          </template>
          <template #default>下载账单</template>
        </a-button>
      </template>

      <template #platform="{ record }">
        <GiCellTag :value="record.platform" :dict="platform_type"/>
      </template>

      <template #status="{ record }">
        <GiCellTag :value="record.status" :dict="settlement_status"/>
      </template>

      <template #song="{ record }">
        <a-typography-paragraph :ellipsis="{rows: 1,showTooltip: true,css: true}">
          {{ record.song }}
        </a-typography-paragraph>
      </template>

      <template #singer="{ record }">
        <a-typography-paragraph :ellipsis="{rows: 1,showTooltip: true,css: true}">
          {{ record.singer }}
        </a-typography-paragraph>
      </template>

      <template #album="{ record }">
        <a-typography-paragraph :ellipsis="{rows: 1,showTooltip: true,css: true}">
          {{ record.album }}
        </a-typography-paragraph>
      </template>

      <template #belongToName="{ record }">
        <a-typography-paragraph v-if="record.belongToName" :ellipsis="{rows: 1,showTooltip: true,css: true}"
                                style="color: #1890ff">
          {{ record.belongToName }}
        </a-typography-paragraph>

        <a-typography-paragraph v-else :ellipsis="{rows: 1,showTooltip: true,css: true}" style="color: #999">
          暂未匹配
        </a-typography-paragraph>
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['settlement:report:get']" title="详情" @click="onDetail(record)">详情</a-link>
          <a-link v-permission="['settlement:report:update']" title="修改" @click="onUpdate(record)">修改</a-link>
          <a-link
              v-permission="['settlement:report:delete']"
              status="danger"
              :disabled="record.disabled"
              :title="record.disabled ? '不可删除' : '删除'"
              @click="onDelete(record)"
          >
            删除
          </a-link>
        </a-space>
      </template>
    </GiTable>

    <SettlementAddModal ref="SettlementAddModalRef" @save-success="search"/>
    <SettlementImportDrawer ref="SettlementImportDrawerRef" @save-success="search"/>
    <SettlementDetailDrawer ref="SettlementDetailDrawerRef"/>
  </div>
</template>

<script setup lang="ts">
import type {TableInstance} from '@arco-design/web-vue'
import SettlementAddModal from './SettlementAddModal.vue'
import SettlementDetailDrawer from './SettlementDetailDrawer.vue'
import SettlementImportDrawer from './settlementImportDrawer.vue'
import {
  type SettlementResp,
  type SettlementQuery,
  deleteSettlement,
  exportSettlement,
  listSettlement
} from '@/apis/settlement/report'
import {useDownload, useTable} from '@/hooks'
import {useDict} from '@/hooks/app'
import {isMobile} from '@/utils'
import has from '@/utils/has'
import dayjs from "dayjs";
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import {Modal} from "@arco-design/web-vue";

defineOptions({name: 'Settlement'})

const {
  settlement_status,
  platform_type,
  username_type,
  channel_type
} = useDict('settlement_status', 'platform_type', 'username_type', 'channel_type')

const queryForm = reactive<SettlementQuery>({
  platform: undefined,
  channel: undefined,
  song: undefined,
  status: undefined,
  belongTo: undefined,
  payDateStart: undefined,
  payDateEnd: undefined,
  sort: ['status,desc', 'payDateStart,asc', 'song,asc', 'cpInto,desc',]
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) => listSettlement({...queryForm, ...page}), {immediate: true})
const columns: TableInstance['columns'] = [
  {
    title: '序号',
    width: 75,
    align: 'center',
    render: ({rowIndex}) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize),
    fixed: !isMobile() ? 'left' : undefined,
  },
  // {title: '结算期间', width: 110, dataIndex: 'payDateStart', slotName: 'payDateStart'},
  // {title: '结算期间', width: 110, dataIndex: 'payDateEnd', slotName: 'payDateEnd'},
  {
    title: '结算期间',
    width: 180,
    dataIndex: 'payDate',
    slotName: 'payDateEnd',
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    }
  },
  {
    title: '平台',  dataIndex: 'platform', slotName: 'platform', align: 'center'
  },
  {
    title: '歌曲名称',  dataIndex: 'song', slotName: 'song', align: 'center'
  },
  {
    title: '歌手名称',  dataIndex: 'singer', slotName: 'singer', align: 'center'
  },
  {
    title: '专辑名称',   dataIndex: 'album', slotName: 'album', align: 'center'
  },
  {
    title: 'CP分成(￥)',
    dataIndex: 'cpInto',
    slotName: 'cpInto',
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    }
  },
  {
    title: '艺人归属',
    dataIndex: 'belongToName',
    slotName: 'belongToName',
    align: 'center',
    sortable: {
      sortDirections: ['ascend', 'descend'],
    }
  },
  {title: '状态', dataIndex: 'status', slotName: 'status', align: 'center'},
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 160,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['settlement:report:get', 'settlement:report:update', 'settlement:report:delete'])
  }
]

// 重置
const reset = () => {
  queryForm.platform = undefined
  queryForm.channel = undefined
  queryForm.status = undefined
  queryForm.song = undefined
  queryForm.belongTo = undefined
  queryForm.status = undefined
  queryForm.payDateStart = undefined
  queryForm.payDateEnd = undefined
  search()
}

// 删除
const onDelete = (record: SettlementResp) => {
  return handleDelete(() => deleteSettlement(record.id), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

// 导出
const onExport = () => {
  queryForm.userId = queryForm.belongTo
  Modal.warning({
    title: '提示',
    content: '是否确认下载账单',
    okButtonProps: {status: 'danger'},
    hideCancel: false,
    maskClosable: false,
    onBeforeOk: () => {
      try {
        useDownload(() => exportSettlement(queryForm))
        return true
      } catch (error) {
        return false
      }
    },
  })
}

const SettlementAddModalRef = ref<InstanceType<typeof SettlementAddModal>>()
// 新增
const onAdd = () => {
  SettlementAddModalRef.value?.onAdd()
}

// 修改
const onUpdate = (record: SettlementResp) => {
  SettlementAddModalRef.value?.onUpdate(record.id)
}

const SettlementImportDrawerRef = ref<InstanceType<typeof SettlementImportDrawer>>()
// 导入
const onImport = () => {


  SettlementImportDrawerRef.value?.onOpen()
}

const SettlementDetailDrawerRef = ref<InstanceType<typeof SettlementDetailDrawer>>()
// 详情
const onDetail = (record: SettlementResp) => {
  SettlementDetailDrawerRef.value?.onOpen(record.id)
}

//日期选择器变化
const onDateChange = (date: Date | [Date, Date]) => {
  console.log(date)
  queryForm.payDateStart = dayjs(date[0]).startOf('month').format('YYYY-MM-DD')
  queryForm.payDateEnd = dayjs(date[1]).add(1, 'month').startOf('month').format('YYYY-MM-DD')
  console.log(queryForm.payDateStart, queryForm.payDateEnd)
  search()
}
</script>

<style scoped lang="scss"></style>
